from textual import on, work
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Markdown, ListView, ListItem, Label, Static, Input, TextArea
from textual.containers import VerticalScroll, Horizontal, Container
from textual.binding import Binding

from dataclasses import dataclass, asdict
from typing import List, Any

import html
from time import monotonic

@dataclass
class Pastebin:
    id         : int # 0
    title      : str # "欢迎查看 Pastebin 片段"
    content    : str # "今天买了台服务器，花了我 99 块。"
    author     : str # "麻师"
    tags       : str # "note"
    syntax     : str # "plaintext"
    theme      : str # "default.css"
    created_at : str # "2024-10-23T20:20:55.195366016+08:00"
    uuid       : str # "c063a69108f6d2cd034b7c75c7b0451a"
    puid       : str # ""
    Pastebin   : Any # null

class WikiApi:

    API = "http://118.178.197.102:8080/pastebin/api"

    def __init__(self):
        self.data : List[Pastebin] = []

    def load(self):
        import requests
        
        resp = requests.get(self.API + '/all')
        
        if resp.status_code == 200:
            self.data.clear()

            for item in resp.json():
                if isinstance(item, dict):
                    print(item)
                    self.data.append(Pastebin(**dict(item)))
        else:
            print("Error:", resp.status_code)

class WikiItem(ListItem):

    def __init__(self, pastebin: Pastebin, index = -1):
        self.pastebin = pastebin
        if index == -1:
            super().__init__(Label(f'{pastebin.id}. {pastebin.title}'))
        else:
            super().__init__(Label(f"{index}. {pastebin.title}"))
            

class WikiApp(App):

    CSS_PATH = "wiki.css"

    BINDINGS = [
        Binding("ctrl+r", "reload", "Reload"),
    ]

    def __init__(self):
        super().__init__()
        self.api = WikiApi()
    
    def compose(self) -> ComposeResult:
        yield Header()
        with Horizontal():
            with Container(classes='list', id='wikilist'):
                yield Input()
                yield ListView()
            with Container(classes='view', id='wikiview'):
                with VerticalScroll():
                    yield TextArea(read_only=True)
        yield Footer()

    def on_mount(self) -> None:
        ''''''
        self.listview = self.query_one(ListView)
        self.view = self.query_one(TextArea)
        
        self.list_container = self.query_one('#wikilist')
        self.list_container.border_title = "Wiki 列表"
        self.view_container = self.query_one('#wikiview')
        self.view_container.border_title = "Wiki 内容"

        self.load_wikis()

    @work(thread=True)
    def load_wikis(self):
        self.start = monotonic()
        self.api.load()
        self.call_from_thread(self.reload)


    def action_reload(self):
        self.load_wikis()

    def reload(self):
        '''重新加载'''
        self.end = monotonic()
        self.listview.clear()
        for index, item in enumerate(self.api.data):
            self.listview.append(WikiItem(item, index))
        self.listview.refresh()
        
        if len(self.api.data) > 0:
            first = self.api.data[0]
            self.view_wiki(first.uuid)
        '''显示第一个'''
        
        self.notify(f"wiki loaded: {len(self.api.data)} 耗时: {self.end - self.start:.2f}ms")

    def on_input_changed(self, event: Input.Changed) -> None:
        '''当输入内容时'''
        for node in self.listview._nodes:
            item : WikiItem = node
            if event.value.lower() in item.pastebin.title.lower():
                node.remove_class("hide")
            else:
                node.add_class("hide")

    @on(ListView.Selected)
    def selected(self, event: ListView.Selected):
        item : WikiItem =  event.item 
        self.notify(f"id: {item.pastebin.title}", timeout=0.5)
        self.view_wiki(item.pastebin.uuid)
    
    @work(thread=True)
    def view_wiki(self, uuid:str):
        for item in self.api.data:
            if item.uuid == uuid:
                self.call_from_thread(self.view.load_text, html.unescape(item.content))
        

if __name__ == "__main__":
    # api = WikiApi()
    # api.load()
    app = WikiApp()
    app.title = 'Pastebin App'.title()
    app.sub_title = '麻师日记'
    app.run()

# 
# curl 'http://192.168.10.75:8080/pastebin/api/all' | jq .[0]

# {
#   "id": 2,
#   "title": "欢迎查看 Pastebin 片段",
#   "content": "今天买了台服务器，花了我 99 块。",
#   "author": "麻师",
#   "tags": "note",
#   "syntax": "plaintext",
#   "theme": "default.css",
#   "created_at": "2024-10-23T20:20:55.195366016+08:00",
#   "uuid": "c063a69108f6d2cd034b7c75c7b0451a",
#   "puid": "",
#   "Pastebin": null
# }